/*
 * @Author: wangyongcun
 * @Date: 2023-09-06 10:50:08
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-09-16 21:02:24
 * @Description: 用户管理
 */
class User {
  constructor() {}
  /**
   * @description: 添加用户信息
   * @param {*} ctx
   * @return {*}
   */
  async addUser(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["phone", "password", "realName"], ctx);
      if (isEmpty) return;

      // 添加到数据库
      let rowBody = ctx.request.body;
      delete rowBody.rePassword;
      // 查询数据是否已存在
      let countSql = `SELECT COUNT(1) FROM user WHERE phone='${rowBody.phone}'`;
      let { status: countStatus, results: countRes } = await db(countSql);
      if (countStatus != 200) throw "查询总条数失败";
      if (countRes[0]["COUNT(1)"] > 0) throw "该用户已存在";
      let rowBodyKeys = Object.keys(rowBody);
      let sqlParams = `id='${uuidv4()}',`;
      rowBodyKeys.forEach((key, index) => {
        let val = rowBody[key];
        if (Array.isArray(val)) {
          val = JSON.stringify(val);
        }
        sqlParams += `${key}='${val}'${
          index == rowBodyKeys.length - 1 ? "" : ","
        }`;
      });
      let sql = `INSERT INTO user SET ${sqlParams}`;
      let { status } = await db(sql);
      if (status != 200) throw "添加用户失败";
      // 返回结果
      ctx.body = resUtil.success("添加成功");
    } catch (err) {
      log.error(`User-addUser-登录失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 更新用户信息
   * @param {*} ctx
   * @return {*}
   */
  async updateUser(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 添加到数据库
      let rowBody = ctx.request.body;
      let rowBodyKeys = Object.keys(rowBody);
      let sqlParams = "";
      rowBodyKeys.forEach((key, index) => {
        let val = rowBody[key];
        if (Array.isArray(val)) {
          val = JSON.stringify(val);
        }
        sqlParams += `${key}='${val}'${
          index == rowBodyKeys.length - 1 ? "" : ","
        }`;
      });
      let sql = `UPDATE user SET ${sqlParams} WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      if (status != 200 || results.affectedRows == 0) throw "更新用户失败";
      // 返回结果
      ctx.body = resUtil.success("更新成功");
    } catch (err) {
      log.error(`User-updateUser-更新失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 删除用户
   * @param {*} ctx
   * @return {*}
   */
  async deleteUser(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 添加到数据库
      let rowBody = ctx.request.body;
      let sql = `DELETE FROM user WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      if (status != 200 || results.affectedRows == 0) throw "未找到该用户";
      // 返回结果
      ctx.body = resUtil.success("删除成功");
    } catch (err) {
      log.error(`User-deleteUser-删除失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 查询用户信息
   * @param {*} ctx
   * @return {*}
   */
  async queryUser(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["id"], ctx);
      if (isEmpty) return;
      // 添加到数据库
      let rowBody = ctx.request.body;
      let sql = `SELECT * FROM user WHERE id='${rowBody.id}'`;
      let { status, results } = await db(sql);
      console.log(results, "results");
      if (status != 200 || results.length == 0) throw "未找到该用户";
      // 返回结果
      ctx.body = resUtil.success({ Content: results[0] });
    } catch (err) {
      log.error(`User-queryUser-查询失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
  /**
   * @description: 查询用户列表
   * @param {*} ctx
   * @return {*}
   */
  async queryUserList(ctx) {
    try {
      // 获取参数
      let isEmpty = reqUtil.isEmpty(["pageNum", "pageSize"], ctx);
      if (isEmpty) return;
      let { pageNum, pageSize, keyword } = ctx.request.body;
      let whereSql = keyword
        ? `WHERE phone LIKE '%${keyword}%' OR realName LIKE '%${keyword}%'`
        : "";
      // 查询总条数
      let Count = 0;
      let countSql = `SELECT COUNT(1) FROM user ${whereSql}`;
      let { status: countStatus, results: countRes } = await db(countSql);
      if (countStatus != 200) throw "查询总条数失败";
      Count = countRes[0]["COUNT(1)"];
      // 查询列表数据
      let listSql = `SELECT * FROM user ${whereSql} ORDER BY updateTime DESC LIMIT ${pageSize} OFFSET ${
        pageSize * (pageNum - 1)
      }`;
      let { status: listStatus, results: listRes } = await db(listSql);
      if (listStatus != 200) throw "查询用户列表失败";
      // 返回结果
      ctx.body = resUtil.success({ Content: listRes, Count });
    } catch (err) {
      log.error(`User-queryUser-查询失败：${err}`);
      ctx.body = resUtil.error(err);
    }
  }
}

export default new User();
